'use strict';

const Controller = require('egg').Controller;

class CategoryController extends Controller {
  // 获取分类列表
  async index() {
    const { ctx } = this;

    try {
      const categories = await ctx.model.Category.findAll({
        where: { is_active: true },
        order: [['level', 'ASC'], ['sort_order', 'ASC']],
      });

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: categories,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取分类详情
  async show() {
    const { ctx } = this;
    const categoryId = ctx.params.id;

    try {
      const category = await ctx.model.Category.findByPk(categoryId);
      if (!category) {
        ctx.throw(404, '分类不存在');
      }

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: category,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 创建分类
  async create() {
    const { ctx } = this;

    ctx.validate({
      name: { type: 'string', required: true, max: 50 },
      parent_id: { type: 'int', required: false },
      level: { type: 'int', required: false },
    });

    try {
      const categoryData = ctx.request.body;
      const category = await ctx.model.Category.create(categoryData);

      ctx.body = {
        code: 200,
        message: '创建成功',
        data: category,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 更新分类
  async update() {
    const { ctx } = this;
    const categoryId = ctx.params.id;

    try {
      const category = await ctx.model.Category.findByPk(categoryId);
      if (!category) {
        ctx.throw(404, '分类不存在');
      }

      const updateData = ctx.request.body;
      await ctx.model.Category.update(updateData, {
        where: { id: categoryId },
      });

      ctx.body = {
        code: 200,
        message: '更新成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 删除分类
  async destroy() {
    const { ctx } = this;
    const categoryId = ctx.params.id;

    try {
      const category = await ctx.model.Category.findByPk(categoryId);
      if (!category) {
        ctx.throw(404, '分类不存在');
      }

      await ctx.model.Category.destroy({
        where: { id: categoryId },
      });

      ctx.body = {
        code: 200,
        message: '删除成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }
}

module.exports = CategoryController;
